import { defineStore } from 'pinia'
import { login, loginByToken } from '@/api/Auth.js'

export const authstore = defineStore('authstore', {
  state() {
    return {
      token: '',
      userinfo: {},
      roles: []
    }
  },
  actions: {
    addToken(token) {
      this.token = token
    },
    // 用户密码登录
    async userlogin(userForm) {
      let res = await login(userForm)
      if (!res) {
        ElMessage.error('账号或密码错误')
        return
      } else {
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        // console.log(res);
        this.token = res.data.token
        this.userinfo = res.data
        console.log(res);
        localStorage.setItem('token', res.data.token)
        return 'ok'
      }


    },
    // token登录
    async userloginByToken(token) {
      let res = await loginByToken(token)
      // console.log(res);
      if (res) {
        this.token = res.data.token
        this.userinfo = res.data
        // console.log('hah ', res.data);
        localStorage.setItem('token', res.data.token)
      } else {
        localStorage.removeItem('token')
      }

    }
  },
  getters: {
    getToken() {
      return this.token
    }
  }

})